<template>
  <div>
    <el-card style="height: 80px">
      <el-form :inline="true" class="form">
        <el-form-item label="用户名:">
          <el-input
            v-model="keyword"
            placeholder="请你输入搜索用户的名字"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            :disabled="keyword === ''"
            size="default"
            @click="search"
          >
            搜索
          </el-button>
          <el-button type="primary" size="default" @click="reset">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card style="margin: 10px 0">
      <el-button type="primary" size="default" @click="addUser">
        添加用户
      </el-button>
      <el-button
        type="primary"
        size="default"
        @click="deleteSelectUser"
        :disabled="selectIdArr.length ? false : true"
      >
        批量删除
      </el-button>
      <!-- table展示用户的信息 -->
      <el-table
        style="margin: 10px 0"
        :data="userArr"
        border
        @selection-change="selectChange"
      >
        <el-table-column type="selection" align="center"></el-table-column>
        <el-table-column
          label="#"
          type="index"
          align="center"
        ></el-table-column>
        <el-table-column label="id" prop="id" align="center"></el-table-column>
        <el-table-column
          label="用户名字"
          prop="userName"
          align="center"
        ></el-table-column>
        <el-table-column
          label="用户名称"
          prop="name"
          align="center"
        ></el-table-column>
        <el-table-column
          label="用户角色"
          prop="roleName"
          align="center"
        ></el-table-column>
        <el-table-column
          label="创建时间"
          :show-overflow-tooltip="true"
          prop="createTime"
          align="center"
        ></el-table-column>
        <el-table-column
          label="更新时间"
          :show-overflow-tooltip="true"
          prop="updateTime"
          align="center"
        ></el-table-column>
        <el-table-column label="操作" width="300px" align="center">
          <template #="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="setRole(row)"
              icon="Avatar"
            >
              分配角色
            </el-button>
            <el-button
              type="primary"
              size="small"
              @click="updateUser(row)"
              icon="Edit"
            >
              编辑
            </el-button>
            <el-popconfirm
              :title="`确认删除吗${row.id}吗？`"
              width="260px"
              @confirm="deleteUser(row.id)"
            >
              <template #reference>
                <el-button type="primary" size="small" @click="" icon="Delete">
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="pageNo"
        v-model:page-size="pageSize"
        :page-sizes="[3, 5, 7, 9]"
        :background="true"
        layout=" prev, pager, next, jumper,->, sizes,total"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="getHasUser"
      />
    </el-card>
    <!-- 抽屉结构：完成添加新的用户账号|更新已有的账号信息 -->
    <el-drawer v-model="drawer">
      <!-- 头部标题 -->
      <template #header>
        <h4>{{ userParams.id ? '更新用户' : '添加用户' }}</h4>
      </template>
      <!-- 身体部分 -->
      <template #default>
        <el-form :model="userParams" :rules="rules" ref="formRef">
          <el-form-item label="用户姓名" prop="username">
            <el-input
              v-model="userParams.username"
              placeholder="请输入姓名"
            ></el-input>
          </el-form-item>
          <el-form-item label="用户昵称" prop="name">
            <el-input
              v-model="userParams.name"
              placeholder="请输入昵称"
            ></el-input>
          </el-form-item>
          <el-form-item v-if="!userParams.id" label="用户密码" prop="password">
            <el-input
              v-model="userParams.password"
              placeholder="请输入密码"
            ></el-input>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button type="primary" size="default" @click="cancel">
            取消
          </el-button>
          <el-button type="primary" size="default" @click="save">
            确定
          </el-button>
        </div>
      </template>
    </el-drawer>
    <!-- 抽屉结构：用于用户某一个账号进行职位的分配 -->
    <el-drawer v-model="drawer1">
      <template #header>
        <h4>分配角色用户</h4>
      </template>
      <template #default>
        <el-form>
          <el-form-item label="用户姓名">
            <el-input :disabled="true" v-model="userParams.roleName"></el-input>
          </el-form-item>
          <el-form-item label="职位列表">
            <el-checkbox
              v-model="checkAll"
              label="全选"
              :indeterminate="indeterminate"
              @change="handleCheckAllChange"
            >
              全选
            </el-checkbox>
            <el-checkbox-group
              @change="handleCheckedCitiesChange"
              v-model="userRole"
            >
              <el-checkbox v-for="item in allRole" :key="item" :value="item">
                {{ item.roleName }}
              </el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </template>
      <template #footer>
        <div style="flex: auto">
          <el-button type="primary" size="default" @click="drawer1 = false">
            取消
          </el-button>
          <el-button type="primary" size="default" @click="confirmClick">
            确定
          </el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive, nextTick } from 'vue'
//仓库
import useLayOutSettingStore from '@/store/modules/setting'
//api
import {
  reqUserInfo,
  reqAddOrUpdateUser,
  reqAllRole,
  reqSetUserRole,
  reqRemoveUser,
  reqSelectUser,
} from '@/apis/acl/user/index'
//引入类型
import type {
  UserResponseData,
  Records,
  User,
  AllRoleResponseData,
  AllRole,
  SetRoleData,
} from '@/apis/acl/user/type'
import { ElMessage } from 'element-plus'

//获取模板setting仓库
let settingStore = useLayOutSettingStore()

//默认页码
let pageNo = ref<number>(1)
//一页展示几条数据
let pageSize = ref<number>(5)

//用户总个数
let total = ref<number>(0)
//存储全部用户的信息
let userArr = ref<Records>([])
//定义响应式数据控制抽屉显示与隐藏
let drawer = ref<boolean>(false)
let drawer1 = ref<boolean>(false)
//收集用户信息的响应式数据
let userParams = reactive<User>({
  username: '',
  name: '',
  password: '',
})
//获取form组件实例
let formRef = ref<any>()

//全选框手机数据是否全选
let checkAll = ref<boolean>(false)
//设置不确定的样式状态
let indeterminate = ref<boolean>(false)

//存储用户已有职位的数据
let allRole = ref<AllRole>([])
//当前用户已有的职位
let userRole = ref<AllRole>([])
//准备一个数组存储批量删除的用户的ID
let selectIdArr = ref<User[]>([])
//收集用户输入进来的关键字
let keyword = ref<string>('')

// //设置所有职位
// const allRoles = ref<string[]>(['销售','前台','财务','boss'])

// const userRoles = ref<string[]>(['销售'])

//获取用户信息
const getHasUser = async (pager = 1) => {
  //收集页码
  pageNo.value = pager

  let result: UserResponseData = await reqUserInfo(
    pageNo.value,
    pageSize.value,
    keyword.value,
  )

  if (result.code === 200) {
    total.value = result.data.total
    userArr.value = result.data.records
  }
}

//分页器下拉菜单事件回调
const handleSizeChange = () => {
  getHasUser()
}

//添加用户按钮的回调
const addUser = () => {
  //每次点击清空数据
  Object.assign(userParams, {
    id: 0,
    username: '',
    name: '',
    password: '',
  })
  //清除验证信息
  nextTick(() => {
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
    formRef.value.clearValidate('password')
  })

  //抽屉显示出来
  drawer.value = true
}

//更新已有用户按钮的回调
const updateUser = (row: User) => {
  //抽屉显示出来
  drawer.value = true
  //存储收集已有的账号信息
  Object.assign(userParams, row)

  //清除验证信息
  nextTick(() => {
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
  })
}

//保存按钮的回调
const save = async () => {
  //点击保存按钮，验证表单
  await formRef.value.validate()
  //保存按钮：添加或者更新用户信息
  let result: any = await reqAddOrUpdateUser(userParams)
  console.log(result)
  //添加或者更新成功
  if (result.code === 200) {
    //关闭抽屉
    drawer.value = false
    //提示消息
    ElMessage({
      type: 'success',
      message: userParams.id ? '更新成功' : '添加成功',
    })
    //获取全部用户信息
    // getHasUser(userParams.id?pageNo.value:1)
    //浏览器自动刷新一次
    window.location.reload()
  } else {
    ElMessage({
      type: 'error',
      message: userParams.id ? '更新失败' : '添加失败',
    })
    //关闭抽屉
    // drawer.value= false
  }
}

//取消按钮的回调
const cancel = () => {
  drawer.value = false
}

//删除某一个用户
const deleteUser = async (userId: number) => {
  let result: any = await reqRemoveUser(userId)

  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}

//批量删除按钮的回调
const deleteSelectUser = async () => {
  //整理批量删除的参数
  let idsList: any = selectIdArr.value.map((item) => {
    return item.id
  })
  //批量删除的请求
  let result: any = await reqSelectUser(idsList)
  if (result.code === 200) {
    ElMessage({
      type: 'success',
      message: '删除成功',
    })
    getHasUser(userArr.value.length > 1 ? pageNo.value : pageNo.value - 1)
  } else {
    ElMessage({
      type: 'error',
      message: '删除失败',
    })
  }
}

//搜索按钮的回调
const search = () => {
  //根据关键字获取数据
  getHasUser()
  //清空关键字
  keyword.value = ''
}

//重置按钮的回调
const reset = () => {
  settingStore.refsh = !settingStore.refsh
}

//分配角色按钮的回调
const setRole = async (row: User) => {
  //存储已有的用户信息
  Object.assign(userParams, row)
  //获取全部职位的数据与当前用户已有职位的数据

  let result: AllRoleResponseData = await reqAllRole(userParams.id as number)
  if (result.code === 200) {
    //存储全部的职位
    allRole.value = result.data.allRolesList
    //存储当前用户已有的职位
    userRole.value = result.data.assignRoles
    //抽屉显示出来
    drawer1.value = true
  }
}

//全选复选框的change事件
const handleCheckAllChange = (val: any) => {
  //val为注入的值，checkAll的全选全不选
  if (val) {
    userRole.value = allRole.value
  } else {
    userRole.value = []
  }
  //不确定的样式
  indeterminate.value = false
}

//普通复选框的change事件
const handleCheckedCitiesChange = (val: string[]) => {
  // value:已经勾选的元素数组
  checkAll.value = val.length === allRole.value.length
  indeterminate.value = val.length > 0 && val.length < allRole.value.length
}

//确定按钮的回调（分配职位）
const confirmClick = async () => {
  //收集参数
  let data: SetRoleData = {
    roleIdList: userRole.value.map((item) => item.id as number),
    userId: userParams.id as number,
  }
  //分配职位
  let result = await reqSetUserRole(data)
  if (result.code === 200) {
    //提示信息
    ElMessage({
      type: 'success',
      message: '分配成功',
    })
    //关闭抽屉
    drawer1.value = false
    //获取更新完毕用户的信息,更新完毕留在当前页
    getHasUser(pageNo.value)
  }
}

//table复选框勾选的时候触发的事件
const selectChange = (value: any) => {
  selectIdArr.value = value
}

//校验用户名字的回调函数
const validatorUsername = (_rule: any, value: any, callback: any) => {
  //用户名字，昵称长度至少5位
  if (value.trim().length >= 5) {
    callback()
  } else {
    callback(new Error('用户名至少5位'))
  }
}

const validatorName = (_rule: any, value: any, callback: any) => {
  //用户名字，昵称长度至少5位
  if (value.trim().length >= 5) {
    callback()
  } else {
    callback(new Error('用户昵称至少5位'))
  }
}

const validatorPassword = (_rule: any, value: any, callback: any) => {
  //用户密码，昵称长度至少5位
  if (value.trim().length >= 6) {
    callback()
  } else {
    callback(new Error('用户密码至少6位'))
  }
}

//表单校验规则
let rules = {
  //用户名字
  username: [
    { required: true, trigger: 'blur', message: '用户名必须' },
    { validator: validatorUsername, trigger: 'blur' },
  ],
  //用户名字
  name: [
    { required: true, trigger: 'blur', message: '昵称必须' },
    { validator: validatorName, trigger: 'blur' },
  ],
  password: [
    { required: true, trigger: 'blur', message: '密码必须' },
    { validator: validatorPassword, trigger: 'blur' },
  ],
}

onMounted(() => {
  //获取数据
  getHasUser()
})
</script>

<style lang="scss" scoped>
.form {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>
